package sugar

import (
	"log"
	"os"
	"path/filepath"
	"runtime"
)

func GetFolder(path string) string {

	// 获取文件夹路径
	dir := filepath.Dir(path)

	// 检查路径是否存在
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		// 路径不存在，创建文件夹
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			log.Printf("Error creating directory: %v\n", err)
			return ""
		}
		log.Printf("Successfully Created Directory 【%s】.", dir)
	} else if err != nil {
		// 其他错误
		log.Printf("Error checking directory: %v\n", err)
		return ""
	}

	return path
}

func IsFolderExist(path string) bool {
	// 获取文件夹路径
	dir := filepath.Dir(path)

	_, err := os.Stat(dir)
	return err == nil
}

// GetPkg 获取当前代码所在包的文件夹名称
func GetPkg(skip int) string {
	_, filename, _, _ := runtime.Caller(skip)
	currentPackagePath := filepath.Dir(filename)
	return filepath.Base(currentPackagePath)
}

// GetPkgParent 获取当前代码所在包的上一级文件夹名称
func GetPkgParent(skip int) string {
	_, filename, _, _ := runtime.Caller(skip)
	currentPackagePath := filepath.Dir(filename)
	parentPath := filepath.Dir(currentPackagePath)
	return filepath.Base(parentPath)
}

// GetCurrentProjectPath 获取当前项目根目录
func GetCurrentProjectPath() string {
	wd, err := os.Getwd()
	if err != nil {
		log.Printf("[os.Getwd]异常，%v", err)
		return ""
	}
	absPath, err := filepath.Abs(wd)
	if err != nil {
		log.Printf("[filepath.Abs]异常，%v", err)
		return ""
	}
	return absPath
}

func ScanFolder(path string) []string {

	var files []string
	_ = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			files = append(files, path)
		}
		return nil
	})
	return files
}
